<template>
  <div class="box">
    <SelfAdaption>
      <Form ref="serviceForm" slot="adaption-bar" label-position="top" class="ivu-form-no-margin-bottom" inline>
        <Form-item prop="vsCode" :label="'单位名称：'">
          <Select filterable clearable v-model="buCode" @on-change="changeBus">
            <Option v-for="(item, index) in busData" :value="item.key" :key="item.key">{{ item.value }}</Option>
          </Select>
        </Form-item>

        <Form-item prop="button" class="search-solt-btn  btn-wrap">
          <RPButton text="导出" @click="exportHandler({})" />
        </Form-item>
      </Form>
    </SelfAdaption>

    <div>
      <Table border ref="table" :loading="loading" :columns="columns7" :data="tableValue" :height="tableHeight"></Table>
    </div>

    <Modal v-model="showModal" :title="title" width="1100" :footer-hide="true">
      <Select filterable clearable v-model="searchVal" class="sea-chart" @on-change="change">
        <Option v-for="(item, index) in opList" :value="item.key" :key="item.key">{{ item.value }}</Option>
      </Select>
      <!-- <div class="chart-content"> -->
      <div ref="echart" style="width:1100px;height:450px;"></div>
      <!-- </div> -->
    </Modal>
  </div>
</template>
<script>
import { exportExcel } from '@ripples/core/utils/excel'
import * as echarts from 'echarts'
import dataEleApi from '@/api/dataElement'
import { getBarOption } from './echartOption'
import permission from '@/mixin/permission'
export default {
  name: 'questionnaireStatistic',
  mixins: [permission],
  data() {
    const self = this
    return {
      loading: false,
      showModal: false,
      busData: [],
      rowIndex: 0,
      tableValue: [],
      searchVal: '1',
      tableHeight: 0,
      opList: [
        { key: '1', value: '按单位排序' },
        { key: '2', value: '按数值降序' },
        { key: '3', value: '按数值升序' }
      ],
      chartDataX: [],
      chartDataY: [],
      keyNumber: '',
      title: '数据汇总',
      self: this,
      columns7: [
        {
          align: 'center',
          className: 'table-header-class',
          renderHeader: (h, params) => {
            return h('div', {}, `2024年${this.buName}客户数据调查表`)
          },
          children: [
            {
              title: '序号',
              width: 80,
              key: 'orderNum',
              type: 'index'
            },
            {
              title: '指标名称',
              key: 'indicatorName',
              align: 'right',
              render: (h, params) => {
                if (params.row.tips) {
                  return h('div', [
                    h(
                      'span',
                      {
                        class: {
                          'pre-text': true
                        }
                      },
                      params.row.indicatorName
                    ),

                    h(
                      'Tooltip',
                      {
                        props: {
                          placement: 'right'
                        }
                      },
                      [
                        h(
                          'span',
                          {
                            slot: 'content',
                            style: {
                              // width: params.column._width * 0.85 + 'px',
                              maxWidth: '800px',
                              display: 'inline-block',
                              overflow: 'hidden',
                              textOverflow: 'ellipsis',
                              whiteSpace: 'pre-wrap',
                              wordWrap: 'break-word',
                              textAlign: 'justify'
                            }
                          },
                          params.row.tips
                        ),

                        h('Icon', {
                          props: {
                            type: 'ios-help-circle'
                          }
                        })
                      ]
                    )
                  ])
                } else {
                  return h('div', [
                    h(
                      'span',
                      {
                        class: {
                          'pre-text': true
                        }
                      },
                      params.row.indicatorName
                    )
                  ])
                }
              }
            },
            {
              title: '汇总值',
              key: 'summaryValue',
              render: (h, params) => {
                if (
                  /^-?[0-9]+(.\d*)?([%‰])?$/.test(params.row.summaryValue) &&
                  (this.buCode == 'CR' || !this.buCode) &&
                  !params.row.notClick
                ) {
                  //判断是数字，小数,选择华润集团
                  return h('div', [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'text',
                          size: 'small'
                        },
                        style: {
                          marginRight: '5px'
                        },
                        on: {
                          click: () => {
                            this.show(params)
                          }
                        }
                      },
                      params.row.summaryValue
                    )
                  ])
                } else {
                  return h(
                    'div',
                    {
                      class: {
                        'col-text': params.row.flag ? false : true,
                        'after-text': params.row.flag ? true : false
                      }
                    },
                    [
                      h(
                        'pre',
                        {
                          props: {
                            type: 'text',
                            size: 'small'
                          },
                          class: {
                            'pre-text': true
                          }
                        },
                        params.row.summaryValue
                      )
                    ]
                  )
                }
              }
            },
            {
              title: '备注',
              key: 'remark',
              align: 'left',
              render: (h, params) => {
                if (params.row.showMoreBtn == undefined) {
                  self.$set(params.row, 'showMoreBtn', true)
                  setTimeout(function() {
                    const td = self.$refs['table'].$children[1].$children[params.index].$el
                    if (td.clientHeight < 65) {
                      self.$set(params.row, 'flag', false)
                    }
                    if (td.clientHeight < 60) {
                      self.$set(params.row, 'showMoreBtn', false)
                    }
                  }, 100)
                }

                // if(td && td.clientHeight > 65){
                return h(
                  'div',
                  {
                    style: {
                      // position:"relative",
                      // display: "-webkit-box",
                      // -webkitBoxOrient: "vertical",
                      // -webkitLineClamp: "3",
                      // overflow: "hidden",
                      // textOverflow: "ellipsis"
                    },

                    class: {
                      'col-text': params.row.flag ? false : true,
                      'after-text': params.row.flag ? true : false
                    },
                    on: {
                      click: () => {
                        this.toggleCol(params)
                      }
                    }
                  },
                  [
                    h(
                      'pre',
                      {
                        class: {
                          'pre-text': true
                        },
                        style: {
                          // position:"relative"
                        }
                      },
                      params.row.remark
                    ),
                    h(
                      'div',
                      {
                        class: {
                          'bb-arrow': true
                        },
                        style: {
                          display: params.row.showMoreBtn + '' == 'true' ? 'inline-block' : 'none'
                          // position: "absolute",
                          // right: "5px",
                          // top:" 5px",
                          // lineHeight:"1",
                          // zIndex:"30"
                        }
                      },
                      [
                        h(
                          'i',
                          {
                            class: {
                              'i-arrow': true
                            }
                            // style:{
                            //   transform:"rotate(0deg)",
                            //   fontStyle: "normal",
                            //   textAlign: "center",
                            //   fontSize: "16px",
                            //   fontWeight: "bol",
                            //   padding: "0px 0px",
                            //   borderRadius: "50%",
                            //   width: "20px",
                            //   height: "20px",
                            //   cursor: "pointer",
                            //   display: "block"
                            // }
                          },

                          [
                            h('img', {
                              class: {
                                'img-arrow': true
                              },
                              attrs: {
                                src: require('../../asset/images/arrow.png')
                              }
                              // style:{
                              //   transform:"rotate(0deg)",
                              //   width:"20px",
                              //   height:"20px"
                              // }
                            })
                          ]
                        )
                      ]
                    )
                  ]
                )
                // }else{
                //   return h('div', params.row.remark)
                // }
              }
            }
          ]
        }
      ]
    }
  },
  props: {
    $route: {
      type: Object,
      default: () => {}
    },
    $router: {
      type: Object,
      default: () => {}
    },
    buCode: {
      type: String,
      default: 'CR'
    }, //业务子单元code
    buName: {
      type: String,
      default: '华润集团'
    },
    scrollKey: {
      type: String,
      default: ''
    }
  },
  created() {
    this.columns7[0].children[0].render = undefined
    this.busData = this.$store.state.buList
    this.getSummaryData()
  },

  mounted() {
    this.tableHeight = document.getElementsByClassName('box')[0].clientHeight - 110
    window.onresize = () => {
      return (() => {
        this.tableHeight = document.getElementsByClassName('box')[0].clientHeight - 110
      })()
    }
  },

  methods: {
    getSummaryData() {
      this.loading = true
      dataEleApi.getSummaryData({ buCode: this.buCode, year: 2024 }).then(res => {
        if (res.code == 200 && res.data) {
          this.tableValue = res.data.data || []
          this.$nextTick(() => {
            if (parseInt(this.scrollKey)) {
              setTimeout(() => {
                this.$refs.table.$children[1].$children[parseInt(this.scrollKey)].$el.scrollIntoView()
              }, 200)
            }
          })
        }
        this.loading = false
      })
    },

    show(params) {
      this.rowIndex = params?.index
      this.chartDataX = []
      this.chartDataY = []
      this.keyNumber = params?.row.orderNum //记录查看的是数据的编号;
      const data = this.tableValue.find(item => item.orderNum == params?.row.orderNum).data
      var keys = Object.keys(data)
      for (var i = 0; i < keys.length; i++) {
        this.chartDataX.push(this.busData.find(ele => ele.key == keys[i])?.value)
        this.chartDataY.push(data[keys[i]])
      }
      this.chartDateXSort = structuredClone(this.chartDataX)
      this.chartDataYSort = structuredClone(this.chartDataY)
      this.loadChart()
      this.searchVal = '1'
      this.title = `数据汇总-${params.row.indicatorName}`
      this.showModal = true
    },

    change(val) {
      this.chartDataX = []
      this.chartDataY = []
      if (val == 1) {
        //单位名称排序
        this.chartDataX = this.chartDateXSort?.length ? [...this.chartDateXSort] : []
        this.chartDataY = this.chartDataYSort?.length ? [...this.chartDataYSort] : []
      } else {
        const data = this.tableValue.find(item => item.orderNum == this.keyNumber).data
        const tempObj = Object.keys(data).reduce((acc, key) => {
          acc.push({ org: key, value: data[key] })
          return acc
        }, [])
        const sortedObj = tempObj.sort(function(a, b) {
          return a.value - b.value
        })
        sortedObj.forEach(item => {
          if (val == 3) {
            this.chartDataX.push(this.busData.find(ele => ele.key == item.org)?.value)
            this.chartDataY.push(item.value)
          } else {
            this.chartDataX.unshift(this.busData.find(ele => ele.key == item.org)?.value)
            this.chartDataY.unshift(item.value)
          }
        })
      }
      this.loadChart()
    },

    changeBus(val) {
      this.buName = this.busData.find(ele => ele.key == val)?.value
      this.getSummaryData(val)
    },

    loadChart() {
      if (this.chartDataX?.length && this.chartDataY?.length) {
        this.$nextTick(() => {
          this.initChart()
        })
      }
    },

    initChart() {
      this.echart = null
      this.echart = echarts.init(this.$refs.echart, null, { renderer: 'svg' })
      // 指定图表的配置项和数据
      const option = getBarOption(this.chartDataX, this.chartDataY)
      // 使用刚指定的配置项和数据显示图表。
      option && this.echart.setOption(option, true)

      // 为图表添加点击事件的监听
      this.echart.off('click')
      this.echart.on('click', params => {
        let bu = this.busData.find(item => {
          return item.value == params.name
        })
        window.open(
          this.$router.resolve({
            path: this.$route.path,
            query: {
              keyNumber: this.rowIndex,
              reportName: '2024年华润集团客户数据调查表',
              buCode: bu.key,
              buName: bu.value
            }
          }).href,
          '_blank'
        )
      })
    },

    async exportHandler(empty) {
      await exportExcel(
        this.columns7[0].children.map(v => ({ title: v.title, key: v.key })),
        this.tableValue.map((v, index) => ({
          orderNum: v.orderNum,
          indicatorName: v.indicatorName,
          summaryValue: v.summaryValue,
          remark: v.remark
        })),
        `2024年华润集团客户数据调查表-${this.buName}-${new Date().getTime()}`
      )
    },

    toggleCol(params) {
      let flag = params.row.flag

      let toggle = !flag
      // const td = this.$refs['table'].$children[1].$children[params.index].$el
      // if(td.clientHeight < 65) {
      this.$set(params.row, 'flag', toggle)
      // }
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  width: calc(100% - 20px);
  margin: 0 auto;
  .self-adaption-wrap {
    /deep/.self-adaption-flex-single {
      margin-bottom: 0;
      padding: 0 5px 10px;
      .search-solt-btn {
        .ivu-form-item-content {
          justify-content: flex-end;
        }
      }
    }
  }
}
.sea-chart {
  width: 200px;
}
/deep/.pre-text {
  margin: 0;
  // padding-bottom: 10px;
  font-size: 14px;
  padding-left: 7px;
  color: #333;
  white-space: pre-wrap;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
    'Helvetica Neue', Helvetica, Arial, sans-serif;
}
/deep/ .ivu-tooltip-inner {
  max-width: 500px;
}
.chart-content {
  width: 1100px;
  height: 450px;
}
[v-cloak] {
  display: none;
}
/deep/.col-text {
  padding-right: 26px;
  // position: relative;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  text-overflow: ellipsis;
  // padding-bottom: 16px;
  .i-arrow {
    transform: rotate(0deg);
    // .img-arrow{
    //   transform:rotate(0deg);
    // }
  }
}

/deep/.after-text {
  padding-right: 20px;
  padding-bottom: 16px;
  .i-arrow {
    transform: rotate(180deg);
    // .img-arrow{
    //   transform:rotate(180deg);
    // }
  }
}

/deep/.bb-arrow {
  position: absolute;
  right: 5px;
  top: 5px;
  line-height: 1;
  z-index: 30;
  .i-arrow {
    // transform:rotate(0deg);
    font-style: normal;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
    padding: 0px 0px;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    cursor: pointer;
    display: block;
    .img-arrow {
      width: 100%;
    }
  }
}
/deep/.ivu-table {
  .ivu-table-body {
    tbody {
      tr {
        td {
          &:last-child {
            padding-right: 0 !important;
          }
        }
      }
    }
  }
}
/deep/.ivu-table-cell {
  padding: 10px;
}
/deep/.ivu-table-row {
  position: relative;
}
/deep/.table-header-class {
  padding: 0;
}
/deep/.ivu-table-header thead tr th {
  padding: 0;
}
</style>
